class PlansController < ApplicationController

  before_filter :login_required
  before_filter :student_required, :only=>[:index, :new,:create]
  before_filter :ownership_required, :except=>[:index, :new, :create]

  def index
      if current_user.role == 'student'
          @plans = Plan.find_all_by_student_id(current_student.id)
      elsif current_user.role == 'administrator'
          @plans = Plan.find(:all)
      end
      respond_to do |format|
          format.html # index.html.erb
          format.xml {render :xml=>@plans}
      end
  end

  def show
      # this happens in the before filter
      # @plan = Plan.find(params[:id])
    
      # create a new comment for this plan
      @comment = Comment.new
      @comment.user_id = current_user.id

      # get the planned courses for this plan
      planned_courses = PlannedCourse.find_all_by_plan_id(params[:plan_id])
      @courses = []
      planned_courses.each {|course| @courses.push(Course.find(course.course_id))}

      respond_to do |format|
          format.html # show.html.erb
          format.xml {render :xml=>@plan}
      end
  end

  def new
      @plan = Plan.new
      @plan.student_id = current_student.id
  end

  def create
    @plan = Plan.new(params[:plan])

    respond_to do |format|
      if @plan.save
        flash[:notice] = 'Plan was successfully created.'
        format.html { redirect_to(@plan) }
        format.xml  { render :xml => @plan, :status => :created, :location => @plan }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @plan.errors, :status => :unprocessable_entity }
      end
    end
  end

  def edit
      # this happens in the before filter
      # @plan = Plan.find(params[:id])

      respond_to do |format|
          format.html # edit.html.erb
      end
  end

  def update
      # this happens in the before filter
      # @plan = Plan.find(params[:id])

    respond_to do |format|
      if @plan.update_attributes(params[:plan])
        flash[:notice] = 'Plan was successfully updated.'
        format.html { redirect_to(@plan) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @plan.errors, :status => :unprocessable_entity }
      end
    end
  end

  def destroy
    # this happens in the before filter
    # @plan = Plan.find(params[:id])
    @plan.destroy

    respond_to do |format|
      format.html { redirect_to(plans_url) }
      format.xml  { head :ok }
    end

  end

  private

    def ownership_required
        @plan = Plan.find(params[:id])
        if current_user.role == "administrator"
            return true
        elsif current_student.id != @plan.student_id
            redirect_to(PermissionDeniedURL)
        else
            return true
        end
    end

end
